import { DialogBase } from '../dialogBase';
import { progressStyle } from './progress.css';

let waitingCount = 0;

class ProgressBox extends DialogBase<ProgressBox> {
	get panel(): HTMLElement {
		return this.el.querySelector(':scope>div')!;
	}
	protected render(): Node {
		return (
			<div class={progressStyle}>
				<div tabIndex={0}>
					<p style={{ display: 'none' }}></p>
					<progress max="100"></progress>
				</div>
			</div>
		);
	}

	/**
	 * Update progress info
	 * @param value between 0 and 100
	 * @param message progress message, null or empty string will hidden message, undefined value will keep previous message state.
	 */
	updateProgress(value?: number | null, message?: string | null) {
		if (value === null) {
			this.panel.querySelector('progress')!.removeAttribute('value');
		} else if (typeof value === 'number') {
			const v = Math.max(Math.min(value, 100), 0);
			this.panel.querySelector('progress')!.value = v;
		}
		if (message === undefined) {
			// do nothing for message
		} else if (!message) {
			this.panel.querySelector('p')!.style.display = 'none';
		} else {
			this.panel.querySelector('p')!.style.display = '';
			this.panel.querySelector('p')!.textContent = message;
		}
	}
}

let inst: ProgressBox | null = null;

export const Progress = {
	show() {
		if (waitingCount === 0) {
			waitingCount = 1;
			inst = new ProgressBox({});
			inst.show();
		} else {
			waitingCount++;
		}
	},
	close() {
		if (waitingCount > 0) {
			waitingCount--;
			if (waitingCount === 0) {
				inst?.close();
				inst = null;
			}
		}
	},
	/**
	 * Update progress info
	 * @param value between 0 and 100 or null means indeterminate progress, undefined value will keep previous progress state.
	 * @param message progress message, null or empty string will hidden message, undefined value will keep previous message state.
	 */
	update(value?: number | null, message?: string | null) {
		inst?.updateProgress(value, message);
	},
};
